<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    class="ant-modal2"
    @cancel="handleCancel"
  >
    <a-form :form="form">

      <a-form-item v-show="false">
        <a-input v-decorator="['id']" type="hidden"/>
        <a-input v-decorator="['purchaseOrderId']" type="hidden"/>
      </a-form-item>

      <row-list :col="2">
        <row-item>

          <a-form-item
            label="报销事项"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['item', {rules: [{required: true, message: '报销事项不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in itemMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="报销金额"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="0"
              :step="0.01"
              :formatter="BaseTool.Amount.formatter"
              :parser="BaseTool.Amount.parser"
              v-decorator="['money', {rules: [{required: true, message: '报销金额不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="报销时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
              v-decorator="['payTime', {rules: [{required: true, message: '报销时间不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="发票号码"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['invoiceNo', {rules: [{required: true, message: '发票号码不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="币种"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              @change="changeMoneyType"
              v-decorator="['moneyType', {initialValue: 1, rules: [{required: true, message: '币种不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in moneyTypeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="汇率"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="0"
              :step="0.01"
              v-decorator="['exchangeRate', {rules: [{required: true, message: '汇率不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="经办人"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['executorId', {rules: [{required: true, message: '经办人名称不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="user in users"
                :key="user.userId"
                :label="user.realName"
                :value="user.userId">{{ user.realName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="备注"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-textarea
              v-decorator="['remark']"/>
          </a-form-item>
        </row-item>
      </row-list>
      <a-row class="form-row" :gutter="BaseTool.Constant.row.gutter">
        <a-col :lg="12" :md="12" :sm="24">
          <a-form-item
            label="发票"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <upload-file :max-size="100" ref="upload" @catchFile="catchFile"></upload-file>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addPurchaseReimburse, updatePurchaseReimburse } from '@/api/purchase/purchase-reimburse'
import { queryUser } from '@/api/upms/user'
import { querySysConfig } from '@/api/upms/config'
import UploadFile from '@/components/Upload/UploadFile'

export default {
  name: 'BasePurchaseReimburse',
  components: { UploadFile },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      users: [],
      order: {},
      invoiceUrls: [],
      moneyTypeMap: {},
      invoiceNames: [],
      // 下拉框map
      itemMap: {}

    }
  },
  props: {},
  created () {
    // 下拉框map
    this.itemMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REIMBURSE_ITEM)
    const moneyTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.MONEY_TYPE)
    const newMap = {}
    const moneyTypes = this.$store.getters.userInfo.moneyTypes
    for (let i = 0; i < moneyTypes.length; i++) {
      const value = moneyTypes[i]
      newMap[value] = moneyTypeMap[value]
    }
    this.moneyTypeMap = newMap
    const rateMap = {}
    querySysConfig({}).then(res => {
      res.data.forEach((item) => {
        rateMap[item.code] = item.content
      })
      this.rateMap = rateMap
    })
    queryUser({}).then(res => {
      this.users = res.data
    })
  },
  methods: {
    base (record, order) {
      this.visible = true
      this.order = order
      const { form: { setFieldsValue } } = this
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.$nextTick(() => {
          setFieldsValue({
            purchaseOrderId: order.id,
            moneyType: order.moneyType,
            exchangeRate: order.exchangeRate,
            executorId: this.$store.getters.userInfo.userId
          })
        })
        this.invoiceUrls = []
        this.invoiceNames = []
        this.$refs.upload.base([])
        return
      }
      this.modalTitle = '编辑'
      // 日期处理
      record.payTime = this.BaseTool.Moment(record.payTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'demandPlanId',
          'purchasePlanId',
          'purchaseApplyId',
          'purchaseOrderId',
          'contractId',
          'contractNo',
          'moneyType',
          'exchangeRate',
          'item',
          'money',
          'payTime',
          'invoiceNo',
          'executorId',
          'executorName',
          'invoiceUrl',
          'remark',
          'delFlag'
        ])))
        const fileList = []
        if (record.invoiceUrl) {
          this.invoiceUrls = record.invoiceUrl.split(',')
          this.invoiceNames = record.invoiceName.split(',')
          for (let i = 0; i < this.invoiceUrls.length; i++) {
            fileList.push({
              uid: i,
              name: this.invoiceNames[i],
              status: 'done',
              url: this.invoiceUrls[i],
              originUrl: this.invoiceUrls[i]
            })
          }
        }
        this.$refs.upload.base(fileList)
      })
    },
    changeMoneyType (value) {
      const { form: { setFieldsValue } } = this
      let rate = 1
      if (this.order.projectMoneyType !== value) {
        rate = this.rateMap[this.DictCache.TYPE.MONEY_TYPE + value + '_' + this.order.projectMoneyType] || this.rateMap[this.DictCache.TYPE.MONEY_TYPE + this.order.projectMoneyType + '_' + value]
      }
      setFieldsValue({
        exchangeRate: rate
      })
    },
    catchFile (fileList) {
      const invoiceUrls = []
      const invoiceNames = []
      fileList.forEach((item) => {
        invoiceUrls.push(item.url)
        invoiceNames.push(item.name)
      })
      this.invoiceUrls = invoiceUrls
      this.invoiceNames = invoiceNames
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        // 日期处理
        values.payTime = this.BaseTool.Date.formatter(values.payTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.invoiceUrl = this.invoiceUrls.join(',')
        values.invoiceName = this.invoiceNames.join(',')
        if (this.BaseTool.String.isBlank(values.id)) {
          addPurchaseReimburse(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updatePurchaseReimburse(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    }

  }
}
</script>
